#include "widget_2.h"
#include "ui_widget_2.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <QMovie>
#include <QResizeEvent>

widget_2::widget_2(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::widget_2),
    manager(new QNetworkAccessManager(this)) // 初始化网络管理器
{
    ui->setupUi(this);
    background_main = new QLabel(this);
    QPixmap img_1(":/kk/Home/KK_1.png");
    background_main->setPixmap(img_1);
    background_main->setGeometry(this->rect()); // 填满整个窗口
    background_main->setScaledContents(true);  // 自动拉伸适配窗口大小
    background_main->lower();                  // 将背景设置到最底层


    // 设置GIF动画
    QMovie *gif_kk = new QMovie(":/gif/gif/123.gif");
    ui->label_17->setMovie(gif_kk);
    ui->label_17->setGeometry(this->rect()); // 填满整个窗口
    gif_kk->start();

    // 获取天气数据
    fetchWeather();
}

widget_2::~widget_2()
{
    delete ui;
}
void widget_2::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);            // 调用基类的 resizeEvent 方法
    background_main->setGeometry(this->rect());        // 根据窗口大小调整背景 QLabel 的尺寸
}
void widget_2::fetchWeather()
{
    QUrl url("http://t.weather.itboy.net/api/weather/city/101250101");  // 这里替换为你自己的城市ID
    QNetworkRequest request(url);

    // 当网络请求完成时调用 onFinished 函数
    connect(manager, &QNetworkAccessManager::finished, this, &widget_2::onFinished);

    manager->get(request);  // 发送GET请求
}

const WeatherData &widget_2::getWeatherData() const
{
    return weatherData;
}



void widget_2::onFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "请求失败:" << reply->errorString();
        return;
    }

    QByteArray responseData = reply->readAll();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);

    if (!jsonDoc.isObject()) {
        qDebug() << "无效的JSON响应";
        return;
    }

    QJsonObject jsonObj = jsonDoc.object();

    // 检查status是否为200，表示请求成功
    if (jsonObj.value("status").toInt() == 200) {
        // 获取城市信息并保存到 weatherData
        QJsonObject cityInfo = jsonObj["cityInfo"].toObject();
        weatherData.city = cityInfo["city"].toString();
        weatherData.parent = cityInfo["parent"].toString();
        weatherData.updateTime = cityInfo["updateTime"].toString();

        // 获取当前的天气数据并保存到 weatherData
        QJsonObject dataObj = jsonObj["data"].toObject();
        weatherData.temperature = dataObj["wendu"].toString();
        weatherData.humidity = dataObj["shidu"].toString();
        weatherData.airQuality = dataObj["quality"].toString();
        weatherData.pm25 = dataObj["pm25"].toInt();
        weatherData.pm10 = dataObj["pm10"].toInt();
        weatherData.coldAlert = dataObj["ganmao"].toString();

        // 清空并填充未来几天的天气预报
        weatherData.forecast.clear();
        QJsonArray forecastArray = dataObj["forecast"].toArray();
        for (const QJsonValue &value : forecastArray) {
            QJsonObject forecastObj = value.toObject();
            WeatherData::Forecast forecast;
            forecast.date = forecastObj["date"].toString();
            forecast.high = forecastObj["high"].toString();
            forecast.low = forecastObj["low"].toString();
            forecast.week = forecastObj["week"].toString();
            forecast.type = forecastObj["type"].toString();
            forecast.notice = forecastObj["notice"].toString();
            weatherData.forecast.append(forecast);
        }
        show_data();
        /*
        // 输出存储的数据
        qDebug() << "城市:" << weatherData.city;
        qDebug() << "区域:" << weatherData.parent;
        qDebug() << "更新时间:" << weatherData.updateTime;
        qDebug() << "温度:" << weatherData.temperature;
        qDebug() << "湿度:" << weatherData.humidity;
        qDebug() << "空气质量:" << weatherData.airQuality;
        qDebug() << "PM2.5:" << weatherData.pm25;
        qDebug() << "PM10:" << weatherData.pm10;
        qDebug() << "冷空气预警:" << weatherData.coldAlert;

        // 输出未来几天的天气预报
        for (const auto &forecast : weatherData.forecast) {
            qDebug() << "未来天气预报：" << forecast.date << forecast.week;
            qDebug() << "最高气温:" << forecast.high << ", 最低气温:" << forecast.low;
            qDebug() << "天气类型:" << forecast.type;
            qDebug() << "预警信息:" << forecast.notice;
            qDebug() << "---------------------------------";
        }
        */
    } else {
        qDebug() << "错误: 获取天气数据失败。状态码:" << jsonObj.value("status").toInt();
    }

    reply->deleteLater(); // 释放 reply 对象
}

QPixmap widget_2::Weathegetimg(QString str)
{

    QPixmap img(":/mini/mini/6.png");
    if(str == "晴")
    {
        img.load(":/mini/mini/6.png");
        return img;
    }else  if(str == "多云")
    {
        img.load(":/mini/mini/4.png");
        return img;
    }else if(str == "小雨")
    {
        img.load(":/mini/mini/8.png");
        return img;
    }else if(str == "阴")
    {
        img.load(":/mini/mini/11.png");
        return img;
    }
}

QPixmap widget_2::Weathegetimgbig(QString str)
{
    QPixmap img(":/weather/weather/img12.png");
    if(str == "晴")
    {
        img.load(":/weather/weather/img12.png");
        return img;
    }else  if(str == "多云")
    {
        img.load(":/weather/weather/img20.png");
        return img;
    }else if(str == "小雨")
    {
        img.load(":/weather/weather/img19.png");
        return img;
    }
}
void widget_2::show_data()
{
    // 输出存储的数据
    QList<QList<QLabel*>> allLabels = {
        {ui->label_7, ui->label_11, ui->label_9, ui->label_8, ui->label_12, ui->label_10},  // 组1
        {ui->label_24, ui->label_25, ui->label_26, ui->label_27, ui->label_28, ui->label_29},  // 组2
        {ui->label_30, ui->label_31, ui->label_32, ui->label_33, ui->label_34, ui->label_35},  // 组3
        {ui->label_36, ui->label_37, ui->label_38, ui->label_39, ui->label_40, ui->label_41},  // 组4
        {ui->label_42, ui->label_43, ui->label_44, ui->label_45, ui->label_46, ui->label_47},  // 组5
        {ui->label_13, ui->label_14, ui->label_15, ui->label_16, ui->label_22, ui->label_23}   // 组6
    };

    // 遍历每个天气预报
    int i = 0;
    for (const auto &forecast : weatherData.forecast) {
        if (i >= allLabels.size()) {
            break;  // 如果没有更多的天气预报数据，则退出
        }

        QList<QLabel*> currentGroup = allLabels[i];  // 获取当前组的标签

        if (currentGroup.size() == 6) {
            // 设置每个标签的文本，按顺序为：日期、星期、天气图标、高温、低温、天气类型
            currentGroup[0]->setText(forecast.date);          // 设置日期
            currentGroup[1]->setText(forecast.week);          // 设置星期
            currentGroup[2]->setPixmap( Weathegetimg(forecast.type));          // 设置星期


            currentGroup[3]->setText(forecast.high);          // 设置高温
            currentGroup[4]->setText(forecast.low);           // 设置低温
            currentGroup[5]->setText(forecast.type);          // 设置天气类型

            // 当 i == 0 时特别设置预警信息
            if (i == 0) {
                 ui->label_6->setPixmap(Weathegetimgbig(forecast.type));
                 ui->label_50->setText(forecast.type);
                 ui->label->setText(weatherData.temperature+"℃");
                 ui->label_18->setText(forecast.high);
                 ui->label_20->setText(forecast.low);
               // currentGroup[5]->setText(forecast.notice);   // 设置预警信息
            } else {
               // currentGroup[5]->clear();                   // 其他组不显示预警信息
            }
        }

        i++;  // 继续处理下一个天气数据
    }

    qDebug() << "城市:" << weatherData.city;
    ui->label_3->setText(weatherData.city);
    qDebug() << "区域:" << weatherData.parent;
    ui->label_2->setText(weatherData.parent);
    qDebug() << "更新时间:" << weatherData.updateTime;
    ui->label_5->setText(weatherData.updateTime);
    qDebug() << "温度:" << weatherData.temperature;
    qDebug() << "湿度:" << weatherData.humidity;
    qDebug() << "空气质量:" << weatherData.airQuality;
    qDebug() << "PM2.5:" << weatherData.pm25;
    qDebug() << "PM10:" << weatherData.pm10;
    qDebug() << "冷空气预警:" << weatherData.coldAlert;


    // 输出未来几天的天气预报
    for (const auto &forecast : weatherData.forecast) {
        qDebug() << "未来天气预报：" << forecast.date << forecast.week;
        qDebug() << "最高气温:" << forecast.high << ", 最低气温:" << forecast.low;
        qDebug() << "天气类型:" << forecast.type;
        qDebug() << "预警信息:" << forecast.notice;
        qDebug() << "---------------------------------";
    }
}

void widget_2::on_pushButton_clicked()
{
      fetchWeather();
}
